package com.baidumap.administrator.happystudy.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ab.http.OnMessageResponse;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.ui.CurriculumScheduleActivity;
import com.baidumap.administrator.happystudy.ui.GoodDetailActivity;
import com.baidumap.administrator.happystudy.ui.RestaurantActivity;
import com.baidumap.administrator.happystudy.ui.SolveProblemActivity;
import com.baidumap.administrator.happystudy.ui.SupermarketActivity;
import com.baidumap.administrator.happystudy.ui.SupermarketGaoDeActivity;
import com.baidumap.administrator.happystudy.ui.SupermarketHomeActivity;
import com.baidumap.administrator.happystudy.ui.TeacherDetailActivity;
import com.baidumap.administrator.happystudy.ui.TeacherMoreActivity;
import com.baidumap.administrator.happystudy.ui.WaiMaiGaoDeActivity;
import com.baidumap.administrator.happystudy.adapter.Adapter_GridView;
import com.baidumap.administrator.happystudy.adapter.Adapter_GridView_ShouYe_MakeupBean;
import com.baidumap.administrator.happystudy.adapter.Adapter_GridView_ShouYe_Market;
import com.baidumap.administrator.happystudy.adapter.Adapter_GridView_ShouYe_Product;
import com.baidumap.administrator.happystudy.adapter.Adapter_GridView_ShouYe_Teacher;
import com.baidumap.administrator.happystudy.adapter.Adapter_ViewPager_ShouYe;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseFragment;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.model.IndexHome;
import com.baidumap.administrator.happystudy.model.Item_ViewPagerGridModel;
import com.baidumap.administrator.happystudy.model.Item_ViewPagerGridModel_Market;
import com.baidumap.administrator.happystudy.model.Item_ViewPagerGridModel_MarkeupBean;
import com.baidumap.administrator.happystudy.model.Item_ViewPagerGridModel_Teacher;
import com.baidumap.administrator.happystudy.module.shopcar.MainActivity;
import com.baidumap.administrator.happystudy.utils.GlideUtil;
import com.baidumap.administrator.happystudy.view.MarqueeText;
import com.baidumap.administrator.happystudy.view.SwipyRefreshLayout;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;


public class Fragment1 extends AppBaseFragment implements OnMessageResponse, XBanner.XBannerAdapter {


    @Bind(R.id.laundry_lay)
    LinearLayout laundryLay;
    @Bind(R.id.order_lay)
    LinearLayout orderLay;
    @Bind(R.id.supermarket_lay)
    LinearLayout supermarketLay;
    @Bind(R.id.curriculum_schedule)
    LinearLayout curriculumSchedule;
    @Bind(R.id.ll_1)
    LinearLayout ll_1;
    @Bind(R.id.ll_2)
    LinearLayout ll_2;
    @Bind(R.id.ll_3)
    LinearLayout ll_3;
    @Bind(R.id.ll_4)
    LinearLayout ll_4;
    @Bind(R.id.rl_more) 
    RelativeLayout rlMore;
    private View view;

    @Bind(R.id.menu_gridview)
    GridView mMenuGridView; //分类的九宫格
    private Adapter_GridView mMenuGridViewAdapter; //menu菜单适配器
    private List<String> mMenuName; //menu的名字
    private List<String> mMenuId; //menu的名字
    private List<Integer> mMenuImg; //menu的图片

    private String mCategoryMarket;


    /**
     * 商品，轮播
     */
    private String[] titles = {"美食", "电影", "酒店住宿", "休闲娱乐", "外卖", "自助餐", "KTV", "机票/火车票", "周边游"};

    private List<View> mPagerList;
    private List<Item_ViewPagerGridModel> mDatas;
    private LayoutInflater inflater;
    private int pageCount; //总的页数
    private int pageSize = 3;//每一页显示的个数
    private int curIndex = 0;//当前显示的是第几页
    private Adapter_ViewPager_ShouYe mViewPager;


    @Bind(R.id.viewpagerProduct)
    ViewPager mPagerProduct;
    private Adapter_GridView_ShouYe_Product adapterGridViewShouYeProduct; //商品gridView适配器

    @Bind(R.id.viewpagerMarket)
    ViewPager mPagerMarket;
    private List<Item_ViewPagerGridModel_Market> mDatasMarket;

    private Adapter_GridView_ShouYe_Market adapterGridViewShouYeMarket; //超市gridView适配器

    @Bind(R.id.viewpagerTeacher)
    ViewPager mPagerTeacher;
    private List<Item_ViewPagerGridModel_Teacher> mDatasTeacher;

    private Adapter_GridView_ShouYe_Teacher adapterGridViewShouYeTeacher; //教师gridView适配器

    @Bind(R.id.viewpagerMakeupBean)
    ViewPager mPagerMakeupBean;
    private List<Item_ViewPagerGridModel_MarkeupBean> mDatasMakeupBean;

    private Adapter_GridView_ShouYe_MakeupBean adapterGridViewShouYeMakeupBean; //教师gridView适配器


    @Bind(R.id.xbanner)
    XBanner mXBanner;

    private List<String> mImgesUrl;
    private List<String> mBannerDataList = new ArrayList<>();


    @Bind(R.id.tv_horizonscrolltextview2)
    MarqueeText tv_horizonscrolltextview2;

    @Bind(R.id.main_SwipyRefreshLayout)
    SwipyRefreshLayout mSwipyRefreshLayout;
    private static int currentPage = 1;

    @Override
    public int bindLayout() {
        return R.layout.fragment_one;
    }

    @Override
    public void initView(View view, LayoutInflater inflater) {
        super.initView(view, inflater);
        initMenu();


        // 设置分页第一页的索引 默认为0
        mSwipyRefreshLayout.setFirstIndex(currentPage);
        // 监听事件
        mSwipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(int index) {
                refreshData();
            }
 
            @Override
            public void onLoad(int index) {
                refreshData();
            }
        });


    }

    private void refreshData() {
        currentPage = 1;

        mDatas.clear();
        mDatasMarket.clear();
        mDatasTeacher.clear();
        mDatasMakeupBean.clear();
        mBannerDataList.clear();

        mMenuGridViewAdapter.notifyDataSetChanged();
        adapterGridViewShouYeProduct.notifyDataSetChanged();
        adapterGridViewShouYeMarket.notifyDataSetChanged();
        adapterGridViewShouYeTeacher.notifyDataSetChanged();
        adapterGridViewShouYeMakeupBean.notifyDataSetChanged();
        initHome();
        mSwipyRefreshLayout.setRefreshing(false);
    }

    private void initHorScroll(String content) {
        //水平滚动2
        tv_horizonscrolltextview2.setText(content);
//        tv_horizonscrolltextview2.setText("明天9~17点因维修原因停电 2017-03-04");
        tv_horizonscrolltextview2.startFor0();
    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        initHome();

    }

    private void initHome() {
        //LoadingDialogUtil.showGifdialog(this);
        Api.indexHome(this);
    }

    @OnClick({R.id.laundry_lay, R.id.order_lay, R.id.supermarket_lay, R.id.curriculum_schedule,
            R.id.ll_1, R.id.ll_2, R.id.ll_3, R.id.ll_4, R.id.rl_more,
            R.id.ll4_1, R.id.ll4_2, R.id.ll4_3, R.id.ll4_4, R.id.rl4_more,
            R.id.jieti, R.id.eat1, R.id.eat2, R.id.eat3, R.id.eat_more,
            R.id.market_more, R.id.market1, R.id.market2, R.id.market3, R.id.market4,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.laundry_lay:
                startActivity(new Intent(getActivity(), SupermarketActivity.class));
                break;
            case R.id.order_lay:
                startActivity(new Intent(getActivity(), RestaurantActivity.class));
                break;
            case R.id.supermarket_lay:
                startActivity(new Intent(getActivity(), SupermarketActivity.class));
                break;
            case R.id.curriculum_schedule:
                startActivity(new Intent(getActivity(), CurriculumScheduleActivity.class));
                break;
            case R.id.ll_1://商品
            case R.id.ll_2:
            case R.id.ll_3:
            case R.id.ll_4:
                Intent intent = new Intent(getActivity(), GoodDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_more://更多商品

                for (int i = 0; i < mMenuName.size(); i++) {

                    if (mMenuName.get(i).contains("化妆品")) {
                        mCategoryMarket = mMenuId.get(i);
                        break;
                    }
                }
                Bundle bundle1 = new Bundle();

                bundle1.putString("category_id", mCategoryMarket);
                bundle1.putString("title", "化妆品列表");

                startBundleActivity(bundle1, SupermarketGaoDeActivity.class);
//                Toast.makeText(getActivity(), "商品列表", Toast.LENGTH_SHORT).show();
                break;
            case R.id.ll4_1://老师
            case R.id.ll4_2:
            case R.id.ll4_3:
            case R.id.ll4_4:
                Intent intent1 = new Intent(getActivity(), TeacherDetailActivity.class);
                startActivity(intent1);
                break;
            case R.id.rl4_more://更多老师
                Intent intent2 = new Intent(getActivity(), TeacherMoreActivity.class);
                startActivity(intent2);
                break;
            case R.id.jieti://老师解题
                Intent intent3 = new Intent(getActivity(), SolveProblemActivity.class);
                startActivity(intent3);
                break;
            case R.id.eat1:
            case R.id.eat2:
            case R.id.eat3:
                startActivity(new Intent(getActivity(), GoodDetailActivity.class));
                break;
            case R.id.eat_more:

                for (int i = 0; i < mMenuName.size(); i++) {

                    if (mMenuName.get(i).contains("外卖")) {
                        mCategoryMarket = mMenuId.get(i);
                        break;
                    }
                }
                Bundle bundle = new Bundle();

                bundle.putString("category_id", mCategoryMarket);
                bundle.putString("title", "外卖列表");

                startBundleActivity(bundle, WaiMaiGaoDeActivity.class);
//                Toast.makeText(getActivity(), "更多美食", Toast.LENGTH_SHORT).show();
                break;
            case R.id.market1:
            case R.id.market2:
            case R.id.market3:
            case R.id.market4:
                startActivity(new Intent(getActivity(), SupermarketHomeActivity.class));
                break;
            case R.id.market_more:


                for (int i = 0; i < mMenuName.size(); i++) {

                    if (mMenuName.get(i).contains("超市")) {
                        mCategoryMarket = mMenuId.get(i);
                        break;
                    }
                }
                Bundle bundle2 = new Bundle();

                bundle2.putString("category_id", mCategoryMarket);
                bundle2.putString("title", "超市列表");

                startBundleActivity(bundle2, SupermarketGaoDeActivity.class);
                break;
        }
    }

    /**
     * 初始化menu菜单
     */
    private void initMenu() {
        mMenuName = new ArrayList<>();
        mMenuImg = new ArrayList<>();
        mMenuId = new ArrayList<>();
//        String[] names = {"洗衣", "点餐", "超市"};
//        int[] images = {R.mipmap.xiyi, R.mipmap.diancan, R.mipmap.chaoshi};
//        for (int i = 0; i < 3; i++) {
//            mMenuName.add(names[i]);
//            mMenuImg.add(images[i]);
//        }
        mMenuGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mMenuGridViewAdapter = new Adapter_GridView(getActivity(), mMenuImg, mMenuName);
        mMenuGridView.setAdapter(mMenuGridViewAdapter);
        mMenuGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Bundle bundle = new Bundle();
                bundle.putString("category_id", mMenuId.get(arg2));
                bundle.putString("title", mMenuName.get(arg2));

//                ToastUtil.showMessage(getActivity(), "category_id=" + mMenuName.get(arg2));
                switch (arg2) {
                    case 0:
                        startBundleActivity(bundle, SupermarketGaoDeActivity.class);
                        break;
                    case 1:
                        startBundleActivity(bundle, WaiMaiGaoDeActivity.class);
                        break;
                    case 2:
                        startBundleActivity(bundle, SupermarketGaoDeActivity.class);
                        break;

                }


            }
        });
    }

    /**
     * 初始化最新商品，viewpager、grid
     */
    private void initViewPagerGridGoods() {
        inflater = LayoutInflater.from(getActivity());
        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(mDatas.size() * 1.0 / pageSize);
        mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            adapterGridViewShouYeProduct = new Adapter_GridView_ShouYe_Product(getActivity(), this, mDatas, i, pageSize, sHelper, getOperation());
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.gridview_shouye, mPagerProduct, false);
            gridView.setAdapter(adapterGridViewShouYeProduct);
            mPagerList.add(gridView);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
//                    Toast.makeText(getActivity(), mDatas.get(pos).getGoods_name(), Toast.LENGTH_SHORT).show();

                    Bundle bundle = new Bundle();

                    bundle.putString("product_id", mDatas.get(pos).getGoods_id());

                    startBundleActivity(bundle, GoodDetailActivity.class);
                }
            });
        }
        mViewPager = new Adapter_ViewPager_ShouYe(mPagerList);
        //设置适配器
        mPagerProduct.setAdapter(mViewPager);

    }

    private void initViewPagerGridMarket() {
        inflater = LayoutInflater.from(getActivity());
        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(mDatasMarket.size() * 1.0 / pageSize);
        mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            adapterGridViewShouYeMarket = new Adapter_GridView_ShouYe_Market(getActivity(), this, mDatasMarket, i, pageSize, sHelper, getOperation());
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.gridview_shouye, mPagerMarket, false);
            gridView.setAdapter(adapterGridViewShouYeMarket);
            mPagerList.add(gridView);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
//                    Toast.makeText(getActivity(), mDatasXiYi.get(pos).getGoods_name(), Toast.LENGTH_SHORT).show();

                    Bundle bundle = new Bundle();

                    bundle.putString("shop_id", mDatasMarket.get(pos).getShop_id());
                    bundle.putString("title", mDatasMarket.get(pos).getShop_name());

                    startBundleActivity(bundle, MainActivity.class);
                }
            });
        }
        mViewPager = new Adapter_ViewPager_ShouYe(mPagerList);
        //设置适配器
        mPagerMarket.setAdapter(mViewPager);

    }

    private void initViewPagerGridTeacher() {
        inflater = LayoutInflater.from(getActivity());
        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(mDatasTeacher.size() * 1.0 / pageSize);
        mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            adapterGridViewShouYeTeacher = new Adapter_GridView_ShouYe_Teacher(getActivity(), this, mDatasTeacher, i, pageSize, sHelper, getOperation());
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.gridview_shouye, mPagerTeacher, false);
            gridView.setAdapter(adapterGridViewShouYeTeacher);
            mPagerList.add(gridView);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
//                    Toast.makeText(getActivity(), mDatasXiYi.get(pos).getGoods_name(), Toast.LENGTH_SHORT).show();

                    Bundle bundle = new Bundle();

                    bundle.putString("teacher_id", mDatasTeacher.get(pos).getTeacher_id());

                    startBundleActivity(bundle, TeacherDetailActivity.class);
                }
            });
        }
        mViewPager = new Adapter_ViewPager_ShouYe(mPagerList);
        //设置适配器
        mPagerTeacher.setAdapter(mViewPager);

    }

    private void initViewPagerGridMakeupBean() {
        inflater = LayoutInflater.from(getActivity());
        //总的页数=总数/每页数量，并取整
        pageCount = (int) Math.ceil(mDatasMakeupBean.size() * 1.0 / pageSize);
        mPagerList = new ArrayList<View>();
        for (int i = 0; i < pageCount; i++) {
            adapterGridViewShouYeMakeupBean = new Adapter_GridView_ShouYe_MakeupBean(getActivity(), this, mDatasMakeupBean, i, pageSize, sHelper, getOperation());
            // 每个页面都是inflate出一个新实例
            GridView gridView = (GridView) inflater.inflate(R.layout.gridview_shouye, mPagerMakeupBean, false);
            gridView.setAdapter(adapterGridViewShouYeMakeupBean);
            mPagerList.add(gridView);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
//                    Toast.makeText(getActivity(), mDatasXiYi.get(pos).getGoods_name(), Toast.LENGTH_SHORT).show();

                    Bundle bundle = new Bundle();

                    bundle.putString("shop_id", mDatasMakeupBean.get(pos).getShop_id());
                    bundle.putString("title", mDatasMakeupBean.get(pos).getShop_name());

                    startBundleActivity(bundle, MainActivity.class);
                }
            });
        }
        mViewPager = new Adapter_ViewPager_ShouYe(mPagerList);
        //设置适配器
        mPagerMakeupBean.setAdapter(mViewPager);

    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        if (url.equals(Constant.INDEX_HOME) && jo != null) {
            IndexHome indexHome = new IndexHome(jo.toString());

            if (indexHome != null) {


                if (indexHome.getCode().equals("200")) {


                    initHorScroll(indexHome.getData().getMessage());

                    List<IndexHome.DataBean.CategoryBean> categoryBeanList = indexHome.getData().getCategory();
                    if (categoryBeanList != null) {

                        mMenuName.clear();
                        mMenuId.clear();
                        mMenuImg.clear();
                        int[] images = {R.mipmap.xiyi, R.mipmap.diancan, R.mipmap.chaoshi};
                        for (int i = 0; i < categoryBeanList.size(); i++) {
                            mMenuName.add(categoryBeanList.get(i).getCategory_name());
                            mMenuImg.add(images[i]);
                            mMenuId.add(categoryBeanList.get(i).getCategory_id());
                        }
                        mMenuGridViewAdapter.notifyDataSetChanged();
                    }

                    List<IndexHome.DataBean.ProductBean> productBeanList = indexHome.getData().getProduct();

                    if (productBeanList != null) {

                        mDatas = new ArrayList<>();
                        for (int i = 0; i < productBeanList.size(); i++) {
                            mDatas.add(new Item_ViewPagerGridModel(productBeanList.get(i).getProduct_id(), productBeanList.get(i).getProduct_name(), productBeanList.get(i).getProduct_pic1(), productBeanList.get(i).getPrice_tuangou(), productBeanList.get(i).getPrice()));
                        }
//                    mViewPager.notifyDataSetChanged();
                        initViewPagerGridGoods();

                    }

                    List<IndexHome.DataBean.MarketBean> marketBeanList = indexHome.getData().getMarket();

                    if (marketBeanList != null) {

                        mDatasMarket = new ArrayList<>();
                        for (int i = 0; i < marketBeanList.size(); i++) {
                            mDatasMarket.add(new Item_ViewPagerGridModel_Market(marketBeanList.get(i).getShop_id(), marketBeanList.get(i).getShop_name(), marketBeanList.get(i).getCover(), marketBeanList.get(i).getIntroduce()));
                        }
                        initViewPagerGridMarket();

                    }

                    List<IndexHome.DataBean.TeacherBean> teacherBeanList = indexHome.getData().getTeacher();

                    if (teacherBeanList != null) {

                        mDatasTeacher = new ArrayList<>();
                        for (int i = 0; i < teacherBeanList.size(); i++) {
                            mDatasTeacher.add(new Item_ViewPagerGridModel_Teacher(teacherBeanList.get(i).getTeacher_id(), teacherBeanList.get(i).getPic(), teacherBeanList.get(i).getName(), teacherBeanList.get(i).getType()));
                        }
                        initViewPagerGridTeacher();

                    }
                    List<IndexHome.DataBean.MakeupBean> makeupBeanList = indexHome.getData().getMakeup();

                    if (makeupBeanList != null) {

                        mDatasMakeupBean = new ArrayList<>();
                        for (int i = 0; i < makeupBeanList.size(); i++) {
                            mDatasMakeupBean.add(new Item_ViewPagerGridModel_MarkeupBean(makeupBeanList.get(i).getShop_id(), makeupBeanList.get(i).getShop_name(), makeupBeanList.get(i).getCover(), makeupBeanList.get(i).getIntroduce()));
                        }
                        initViewPagerGridMakeupBean();

                    }
                    List<IndexHome.DataBean.AdvBean> advBeanList = indexHome.getData().getAdv();

                    if (advBeanList != null) {

                        for (int i = 0; i < advBeanList.size(); i++) {

                            mBannerDataList.add(advBeanList.get(i).getImgurl());
                        }
                        initXBanner();


                    }

                }

            }


        }
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }


    /**
     * 初始化轮播图
     */

    private void initXBanner() {

        mImgesUrl = new ArrayList<>();


        for (int i = 0; i < mBannerDataList.size(); i++) {
            mImgesUrl.add(mBannerDataList.get(i));

        }
        //添加广告数据
        mXBanner.setData(mImgesUrl, null);//第二个参数为提示文字资源集合
        mXBanner.setmAdapter(this);
    }

    @Override
    public void loadBanner(XBanner banner, Object model, View view, int position) {

        GlideUtil.displayImgBanner(getActivity(), mImgesUrl.get(position), view);
    }
}
